package com.torlesse.authdemo.aspect;

import com.torlesse.authdemo.pojo.Log;
import com.torlesse.authdemo.service.LogService;
import com.torlesse.authdemo.utlis.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/02/19/17:14
 * @Description:UserController切面类
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LogService logService;

    @Pointcut("(execution(public * com.torlesse.authdemo.controller.*.update*(..)) || " +
            "execution(public * com.torlesse.authdemo.controller.*.del*(..)) ||" +
            "execution(public * com.torlesse.authdemo.controller.*.add*(..))) &&" +
            " !execution(* com.torlesse.authdemo.controller.LoginController.*(..)))")
    public void pointcut(){};

    @After(value = "pointcut()")
    public void around(JoinPoint joinPoint){
        Log log = new Log();
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(token);
        //1、设置用户ID
        Integer uid = Integer.parseInt(claims.getId());
        log.setUid(uid);
        //2、设置操作时间
        log.setHandleTime(new Timestamp(System.currentTimeMillis()));
        //3、设置ip地址
        String ip = request.getRemoteAddr();
        log.setIpAddress(ip);
        //被拦截的对象
        Object target = joinPoint.getTarget();
        //被拦截的类的全限类名
        String className = target.getClass().getName();
        //获取被拦截的方法
        Signature signature = joinPoint.getSignature();
        //获取方法名称
        String methodName = signature.getName();
        //4、设置操作方法
        log.setMethod(className +"."+ methodName);

        //将日志对象存储到数据库中
        logService.saveLog(log);
    }
}
